package cn.com.zpon.shouyinyuandemo.util;

import android.os.AsyncTask;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpUtil {
    
    public static void get(final String url, final HttpCallback callback) {
        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... p) {
                return excute(url, "GET", null);
            }
            
            @Override
            protected void onPostExecute(String result) {
                callback.onFinished(result);
            }
        }.execute();
    }
    
    private static String excute(final String url, String method, final Map<String, String> params) {
        String ret = null;
        HttpURLConnection conn = null;
        InputStream in = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod(method);
            String paramsStr = cn.com.zpon.shouyinyuandemo.util.StringUtils.params2QueryStr(params, false, true);
            if (params != null) {
                PrintWriter pw = new PrintWriter(conn.getOutputStream());
                pw.print(paramsStr);
                pw.flush();
                pw.close();    
            }
            if (conn.getResponseCode()==200){
                in = conn.getInputStream();
                ret = inputStream2Str(in);
            }else{
                ret=null;
            }
        } catch (Exception e) {

        } finally {
            if (in != null) {
                try {
                    in.close();    
                } catch (Exception ex) {
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return ret;
    }
    
    public static void post(final String url, final Map<String, String> params, final HttpCallback callback) {
        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... p) {
                return excute(url, "POST", params);
            }
            
            @Override
            protected void onPostExecute(String result) {
                callback.onFinished(result);
            }
        }.execute();
    }
    
    private static String inputStream2Str(InputStream in) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            return new String(out.toByteArray(), "utf-8");    
        } catch (Exception e) {
            return null;
        }
    }
}
